#include "ScnsAt24c02.c.h"

#if defined(SCNS_AT24C02_ENABLE)&&SCNS_AT24C02_ENABLE==1

//@scnsBsp:https://gitee.com/huoxingdawang/scnsDemos-STM32F767IGT6_AlientekApollo/tree/master/Libraries/scnsBsp/STM32F767IGT6_AlientekApollo/

#include "ScnsTimer.h"
#include "ScnsSmctp.h"

static struct
{
    uint8 inited;
}rd[SCNS_AT24C02_MAX];

static ScnsAt24c02Status WB(ScnsAt24c02Enum at2N,uint8 addr,uint8 data)
{
    return scnsBspAt24c02Write(at2N,&addr,1,&data,1);
}

static uint8 RB(ScnsAt24c02Enum at2N,uint8 addr)
{
    uint8 data=0;
    scnsBspAt24c02Read(at2N,&addr,1,&data,1);
    return data;
}

ScnsAt24c02Status scnsAt24c02Init(ScnsAt24c02Enum at2N)
{
    SCNS_ASSERT_ON_RUN(at2N<SCNS_AT24C02_MAX);
    scnsCheck(ScnsAt24c02Status,scnsBspAt24c02Init(at2N),SCNS_AT24C02_STATUS_OK);
    uint8 addr=0XFF,data=0;
    scnsCheckTimeOut(200*1000,scnsBspAt24c02Read(at2N,&addr,1,&data,1)==SCNS_AT24C02_STATUS_OK,SCNS_AT24C02_STATUS_TIME_OUT);
    scnsCheck(ScnsAt24c02Status,scnsBspAt24c02PostInit(at2N),SCNS_AT24C02_STATUS_OK);
    rd[at2N].inited=1;
    return SCNS_AT24C02_STATUS_OK;
}

uint8 scnsAt24c02ReadByte(ScnsAt24c02Enum at2N,uint8 addr)
{
    SCNS_ASSERT_ON_RUN(at2N<SCNS_AT24C02_MAX);
    if(!rd[at2N].inited)
        return 0;
    return RB(at2N,addr);
}

void scnsAt24c02WriteByte(ScnsAt24c02Enum at2N,uint8 addr,uint8 data)
{
    SCNS_ASSERT_ON_RUN(at2N<SCNS_AT24C02_MAX);
    if(!rd[at2N].inited)
        return;
    WB(at2N,addr,data);
    scnsDelayUs(4000);
}

void scnsAt24c02ReadBytes(ScnsAt24c02Enum at2N,uint8 addr,uint8 data[],uint8 len)
{
    SCNS_ASSERT_ON_RUN(at2N<SCNS_AT24C02_MAX);
    if(!rd[at2N].inited)
        return;
    for(uint8 i=0;i<len;++i)
        data[i]=RB(at2N,addr+i);
}

void scnsAt24c02WriteBytes(ScnsAt24c02Enum at2N,uint8 addr,uint8 data[],uint8 len)
{
    SCNS_ASSERT_ON_RUN(at2N<SCNS_AT24C02_MAX);
    if(!rd[at2N].inited)
        return;
    for(uint8 i=0;i<len;++i)
    {
        WB(at2N,addr+i,data[i]);
        scnsDelayUs(4000);
    }
}

ScnsAt24c02Status scnsAt24c02Test(ScnsAt24c02Enum at2N,uint8 addr)
{
    SCNS_ASSERT_ON_RUN(at2N<SCNS_AT24C02_MAX);
    if(!rd[at2N].inited)
        return SCNS_IIC_STATUS_FAILED;
    uint8 data[16];
    uint8 start=scnsAt24c02ReadByte(at2N,addr)+1;
    for(uint8 i=0;i<16;data[i]=i+start,++i);
#if defined(SCNS_SMCTP_ENABLE)&&SCNS_SMCTP_ENABLE==1
    scnsSmctpPrintBuf(SCNS_SMCTP_CHANNEL_DEBUG,data,16,8);
#endif
    scnsAt24c02WriteBytes(at2N,addr,data,16);
    for(uint8 i=0;i<16;data[i]=0,++i);
    scnsAt24c02ReadBytes(at2N,addr,data,16);
#if defined(SCNS_SMCTP_ENABLE)&&SCNS_SMCTP_ENABLE==1
    scnsSmctpPrintBuf(SCNS_SMCTP_CHANNEL_DEBUG,data,16,8);
#endif
    for(uint8 i=0;i<16;++i)
        if(data[i]!=i+start)
            return SCNS_AT24C02_STATUS_FAILED;
    return SCNS_AT24C02_STATUS_OK;
}

#endif
